package com.banshuibao.bsb_android.activity;

import android.Manifest;
import android.app.AppOpsManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.provider.Settings;
import android.support.v4.app.NotificationManagerCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.banshuibao.bsb_android.MyApplication;
import com.banshuibao.bsb_android.R;
import com.banshuibao.bsb_android.util.CCMediaConfig;
import com.banshuibao.bsb_android.util.DataCleanManager;
import com.banshuibao.bsb_android.util.DialogUtils;
import com.banshuibao.bsb_android.util.GetLoginInfo;
import com.banshuibao.bsb_android.util.IntentManager;
import com.banshuibao.bsb_android.util.VersionCodeUtil2;
import com.suke.widget.SwitchButton;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class SettingActivity extends PermissionBaseActivity implements View.OnClickListener {

    private RelativeLayout clear_cache, update_pwd, about_us, mine_help, update_phone, updata_version, open_infor;
    private TextView log_out;
    private String cookieId;
    private TextView user_phone, version_name;
    private SwitchButton switchButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        cookieId = GetLoginInfo.getLoginInfoInstance(this).readUser().getCookieId();
        initView();
    }

    @Override
    public void successGrantPermission(int requestCode) {
        switch (requestCode) {
            case 210:
                new VersionCodeUtil2(SettingActivity.this).getVersionCode();
                break;
        }
    }

    public void initView() {
        setTitleText("设置");
        clear_cache = findViewById(R.id.clear_cache);
        about_us = findViewById(R.id.about_us);
        update_pwd = findViewById(R.id.update_pwd);
        log_out = findViewById(R.id.log_out);
        mine_help = findViewById(R.id.mine_help);
        update_phone = findViewById(R.id.updata_phone);
        updata_version = findViewById(R.id.update_version);
        open_infor = findViewById(R.id.open_infor);
        version_name = findViewById(R.id.version_name);
        user_phone = findViewById(R.id.user_phone);
        switchButton = findViewById(R.id.sws);

//        switchButton.toggle();     //switch state
//        switchButton.toggle(true);//switch without animation
//        switchButton.setShadowEffect(true);//disable shadow effect
//        switchButton.setEnabled(true);//disable button
//        switchButton.setEnableEffect(true);//disable the switch animation
        boolean b = NotificationManagerCompat.from(this).areNotificationsEnabled();
        if (Build.VERSION.SDK_INT >= 26) {
            if (b) {
                switchButton.setChecked(true);
                switchButton.isChecked();
            } else {
                switchButton.setChecked(false);
            }
        } else if ((Build.VERSION.SDK_INT >= 19)) {
            if (isNotificationEnabled(this)) {
                switchButton.setChecked(true);
                switchButton.isChecked();
            } else {
                switchButton.setChecked(false);
            }
        }
        switchButton.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                //TODO do your job
                if (!isChecked) {
                    goToSet();
                }
            }
        });
        clear_cache.setOnClickListener(this);
        about_us.setOnClickListener(this);
        update_pwd.setOnClickListener(this);
        log_out.setOnClickListener(this);
        mine_help.setOnClickListener(this);
        update_phone.setOnClickListener(this);
        updata_version.setOnClickListener(this);
        //得到当前手机版本号
        try {
            String versionName = getPackageManager().getPackageInfo("com.banshuibao.bsb_android", 0).versionName;
            if (!TextUtils.isEmpty(versionName)) {
                version_name.setText("v" + versionName);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        String phone = GetLoginInfo.getLoginInfoInstance(this).readUser().getPhoneNumber();
        user_phone.setText(phone);

        if (!TextUtils.isEmpty(cookieId)) {
            log_out.setVisibility(View.VISIBLE);
            update_pwd.setVisibility(View.VISIBLE);
            update_phone.setVisibility(View.VISIBLE);
            open_infor.setVisibility(View.VISIBLE);
        } else {
            log_out.setVisibility(View.GONE);
            update_pwd.setVisibility(View.GONE);
            update_phone.setVisibility(View.GONE);
            open_infor.setVisibility(View.GONE);
        }
    }

    //点击进入设置页面
    private void goToSet() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.BASE) {
            // 进入设置系统应用权限界面
            Intent intent = new Intent(Settings.ACTION_SETTINGS);
            intent.setClassName("com.android.settings",
                    "com.android.settings.Settings");
            intent.setAction(Intent.ACTION_MAIN);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                    | Intent.FLAG_ACTIVITY_CLEAR_TASK
                    | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
            intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
                    "com.android.settings.applications.AppOpsSummary");
            startActivity(intent);
            return;
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {// 运行系统在5.x环境使用
            // 进入设置系统应用权限界面
            Intent intent = new Intent(Settings.ACTION_SETTINGS);
            intent.setClassName("com.android.settings",
                    "com.android.settings.Settings");
            intent.setAction(Intent.ACTION_MAIN);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                    | Intent.FLAG_ACTIVITY_CLEAR_TASK
                    | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
            intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
                    "com.android.settings.applications.AppOpsSummary");
            startActivity(intent);
            return;
        }
    }

    //判断通知是否开启
    private boolean isNotificationEnabled(Context context) {

        String CHECK_OP_NO_THROW = "checkOpNoThrow";
        String OP_POST_NOTIFICATION = "OP_POST_NOTIFICATION";

        AppOpsManager mAppOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
        ApplicationInfo appInfo = context.getApplicationInfo();
        String pkg = context.getApplicationContext().getPackageName();
        int uid = appInfo.uid;

        Class appOpsClass = null;
     /* Context.APP_OPS_MANAGER */
        try {
            appOpsClass = Class.forName(AppOpsManager.class.getName());
            Method checkOpNoThrowMethod = appOpsClass.getMethod(CHECK_OP_NO_THROW, Integer.TYPE, Integer.TYPE,
                    String.class);
            Field opPostNotificationValue = appOpsClass.getDeclaredField(OP_POST_NOTIFICATION);

            int value = (Integer) opPostNotificationValue.get(Integer.class);
            return ((Integer) checkOpNoThrowMethod.invoke(mAppOps, value, uid, pkg) == AppOpsManager.MODE_ALLOWED);

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.about_us:
                IntentManager.goAboutUsActivity(this);
                break;
            case R.id.clear_cache:
                DialogUtils.getConfirmDialog(this, "是否清空缓存?", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        DataCleanManager.cleanAllCache(SettingActivity.this);
                    }
                }).show();
                break;
            case R.id.update_pwd:
                if (!TextUtils.isEmpty(cookieId)) {
                    IntentManager.goUpPasswordActivity(this);
                } else {
                    IntentManager.goLoginActivity(this);
                }
                break;
            case R.id.log_out:
                DialogUtils.getConfirmDialog(this, "是否退出登录?", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
//                        if (!TextUtils.isEmpty(role) && role.equals("1")) {
//                            GetLoginInfo.getLoginInfoInstance(SettingActivity.this).clearInfo();
//                            login.setText("登录/");
//                            register.setText("注册");
//                            head_tag.setImageResource(R.drawable.tovip);
//                            head_tag.setVisibility(View.GONE);
//                            login.setClickable(true);
//                            register.setClickable(true);
//                            update_pwd.setVisibility(View.GONE);
//                            log_out.setVisibility(View.GONE);
//                            head_iv.setImageResource(R.drawable.login_iv);
//                            apply_expert.setVisibility(View.GONE);
//                        } else {
                        MyApplication.applicationInstance.deleteTag("0","1", "tax", "user");//1 安卓手机  tax咨询师  user用户
                        MyApplication.applicationInstance.removeAlias(GetLoginInfo.getLoginInfoInstance(SettingActivity.this).readUser().getUserId());
                        GetLoginInfo.getLoginInfoInstance(SettingActivity.this).clearInfo();
                        IntentManager.goUserHomeActivity(SettingActivity.this);
                        sendCancelDownload();
                        if (SettingActivity.this != null)
                            finish();
//                        }
                    }
                }).show();
                break;
            case R.id.mine_help:
                IntentManager.goHelpActivity(this);
                break;
            case R.id.updata_phone:
                IntentManager.goChangePhoneActivity(this);
                break;
            case R.id.update_version:
                requestUserPermission(v, Manifest.permission.WRITE_EXTERNAL_STORAGE, 210);
                break;
        }
    }

    private void sendCancelDownload() {
        Intent it = new Intent(CCMediaConfig.ACTION_DOWNLOADING_CANCEL);
        sendBroadcast(it);
    }

}
